package br.com.emmis.tercons.util;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import br.com.emmis.tercons.constants.Constants;

/**
 * Created by vaner on 03/03/2015.
 */
public class SettingsXMLUtil {

    private int mNodesCount;
    private NodeList mNodes;

    public SettingsXMLUtil(byte[] line) throws IOException, SAXException, ParserConfigurationException {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new ByteArrayInputStream(line)));

        mNodes = doc.getElementsByTagName(Constants.XML_NODE_SETTINGS);
        mNodesCount = mNodes.getLength();
    }

    public String getURL() {
        String url = null;

        if(mNodesCount > 0) {
            Element element = (Element) mNodes.item(0);
            url = element.getElementsByTagName(Constants.XML_NODE_SETTINGS_URL).item(0).getTextContent();
        }
        return url;
    }
}
